<template>
  <div class="app-container">
    <!-- 上传excel -->
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
import UploadExcelComponent from "./components/UploadExcel.vue";
import EmployeeEnum from "@/api/constant/employees";
import { batchImportEmployeeAPI } from "@/api/employees";
import formatDate from "@/utils/formatDate"//时期格式化
import msgTip from "@/utils/message-tip";
export default {
  name: "UploadExcel",
  components: { UploadExcelComponent },
  methods: {
    /**
     * @description 文件上传前大小限制
     * @param {Object} file 
     * @returns Boolean
     */
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1; //上传大小限制
      if (isLt1M) {
        return true;
      }
      msgTip({ msg: "请不要上传大于1M的文件.", type: "warning" });
      return false;
    },
    /**
     * @description 文件上传
     * @param {Object} 
     */
    async handleSuccess({ results, header }) {
      const importData = this.handleChineseToEnglish(results);
      const res = await batchImportEmployeeAPI(importData);
      msgTip({ msg: res.message });
      // this.$router.replace("/employees");
      this.$router.back();
    },
    /**
     * @description 格式化excel数据（中文key => 英文 key）
     * @param {Array:Object} results
     * @returns Array
     */
    handleChineseToEnglish(results) {
      const dataArray = [];
      const timerArray = ["timeOfEntry", "correctionTime"];
      results.forEach((item) => {
        const staffInfo = {}; //员工信息对象
        Object.keys(item).forEach((key) => {//获取excel数据key
          if (timerArray.includes(EmployeeEnum.excel[key])) { //如果含有时间数据====格式化时间
            staffInfo[EmployeeEnum.excel[key]] = formatDate( item[key], "YYYY/MM/DD",true); 
            return;//跳出 Object.keys().forEach本次循环
          }
          if (key=== "聘用形式") {
            for (let index = 0, len = EmployeeEnum.hireType.length;index < len; index++ ) {
              if (item[key] === EmployeeEnum.hireType[index].value) {
                staffInfo[EmployeeEnum.excel[key]] =
                  EmployeeEnum.hireType[index].id;//聘用形式value 转换 （正式 =》 1  非正式 =》2）
                break; //终止for循环
              }
            }
            return;//跳出Object.keys().forEach本次循环
          }

          staffInfo[EmployeeEnum.excel[key]] = item[key]; //中文key => 英文 key
        });
        dataArray.push(staffInfo);
      });
      return dataArray;
    },
    
  },
};
</script>
<style scoped>
.page {
  margin-top: 10px;
}
</style>
